package cn.wangxl.group.rpc.handler;

import cn.wangxl.group.rpc.protocol.MessageProtocol;
import cn.wangxl.group.rpc.register.ServiceObject;
import cn.wangxl.group.rpc.register.ServiceRegister;
import cn.wangxl.group.rpc.rpcEntity.RpcRequest;
import cn.wangxl.group.rpc.rpcEntity.RpcResponse;
import cn.wangxl.group.rpc.rpcEntity.RpcResponseStatus;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Deacription RequestHandler
 * @Author 20112128
 * @Date 2020/9/22 18:25
 **/
public class RequestHandler {

    private ServiceRegister serviceRegister;

    private MessageProtocol messageProtocol;

    public byte[] handleRequest(byte[] requestData) {

        // 解组请求消息
        RpcRequest request = messageProtocol.unmarshallingRequest(requestData);

        // 查找服务对象
        ServiceObject serviceObject = serviceRegister.getServiceObject(request.getServiceName());
        RpcResponse rpcResponse = null;
        if(serviceObject == null){
            rpcResponse = new RpcResponse(RpcResponseStatus.NOT_FOUND);
        }
        try {
            // 反射调用服务
            Method method = serviceObject.getInterf().getMethod(request.getMethod(),request.getParameterTypes());
            Object returnValue = method.invoke(serviceObject.getObject(), request.getParameters());

            rpcResponse = new RpcResponse(RpcResponseStatus.SUCCESS);
            rpcResponse.setReturnValue(returnValue);

        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
            rpcResponse = new RpcResponse(RpcResponseStatus.ERROR);
            rpcResponse.setException(e);
        }

        // 编组响应消息
        return messageProtocol.marshallingResponse(rpcResponse);
    }


    public RequestHandler(ServiceRegister serviceRegister, MessageProtocol messageProtocol) {
        this.serviceRegister = serviceRegister;
        this.messageProtocol = messageProtocol;
    }
}
